package utils

import "sync/atomic"

type ChanTaskList struct {
	taskIdx uint32
	taskn   uint32
	cachen  int
	tasklst []*ChanTask
}

func NewChanTaskList(cachen int) *ChanTaskList {
	rval := &ChanTaskList{cachen: cachen}
	return rval
}

func (this *ChanTaskList) ConfigTaskN(n uint32) {
	if this.taskn != n {
		this.releaseTask()
		this.taskn = n
		this.makeTaskList()
	}
}

func (this *ChanTaskList) releaseTask() {
	for i := 0; i < len(this.tasklst); i++ {
		this.tasklst[i].Stop()
	}
}

func (this *ChanTaskList) makeTaskList() {
	this.tasklst = make([]*ChanTask, this.taskn)
	for i := 0; i < len(this.tasklst); i++ {
		this.tasklst[i] = NewChanTask(this.cachen)
	}
}

func (this *ChanTaskList) CreateTaskIdx() uint32 {
	r := atomic.AddUint32(&this.taskIdx, 1)
	return r
}

func (this *ChanTaskList) CheckGetTask(task *ChanTask, taskIdx uint32) *ChanTask {
	if task == nil || task.Terminated == 1 {
		return this.GetTask(taskIdx)
	}
	return task
}

func (this *ChanTaskList) GetTask(taskIdx uint32) *ChanTask {
	idx := taskIdx % this.taskn
	return this.tasklst[idx]
}
